'''
孝亲宝
'''
import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from common.helper import Helper
from urllib.parse import urlencode


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "孝亲宝"
    def genProductInfo(self):
        plan = {
            "planA":{
                # 年龄段
                "year":[str(i) for i in range(45,66)],
                #性别
                "gender":["M","F"],
                #保险期间
                "expire":["10","20"],
                #缴费间隔
                "interval":["10","20"],
                #保额
                "money":["100000"],
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(66, 76)],
                # 性别
                "gender": ["M", "F"],
                # 保险期间
                "expire": ["10"],
                # 缴费间隔
                "interval": ["10"],
                # 保额
                "money": ["100000"]
            }
        }

        for k in plan:

            for v in product(plan[k]["year"],plan[k]["gender"],plan[k]["expire"],plan[k]["interval"],plan[k]["money"]):

                self.mysql.cursor.execute( domain[self.name]["insert_sql"].format(

                    v[0],v[1],v[2],v[3],v[4]
                ))
                self.mysql._conn.commit()
                print( domain[self.name]["insert_sql"].format(

                    v[0],v[1],v[2],v[3],v[4]
                ) )

    #执行爬虫
    def requestJson(self,dt=None):

        data = {
            "productNo": "11",
            "insuredSex": "0" if dt["gender"]=="M" else "1",
            "insuredBirthday": "{year}-01-16".format(year=str(2020-int(dt["year"]))),
            "insuranceYears": dt["expire"],
            "paymentPeriod": dt["interval"],
            "guaranteeAmount": "100000.00",
            "mult": "0",
            "payIntv": "12",
            "insuyearFlag": "Y",
            "payendyearFlag": "Y",
            "contPlanCode": "nets0030",
        }

        payload = urlencode( data ).replace("+","")
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)

        if r.status_code == 200 and r.json()["flag"]:

            price = Helper.decimalParse( r.json()["result"])

            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )


        else:

            data = {

                "name": self.name,

                "id": dt["id"],

                "state": 3

            }

            self.mysql.updateTask(data)

    def main(self):

        while True:

            # 随机领取一条数据

            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return


                # 任务执行状态

            data = {

                "name": self.name,

                "id": dt["id"],

                "state": 1

            }

            self.mysql.updateTask(data)

            self.requestJson(dt)

